package com.sliansoft.wechat.appcenter.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.sliansoft.wechat.appcenter.exception.SuiteException;
import com.sliansoft.wechat.appcenter.model.AppWithBLOBs;
import com.sliansoft.wechat.appcenter.model.Menuone;
import com.sliansoft.wechat.appcenter.model.Menutwo;
import com.sliansoft.wechat.appcenter.model.SuiteWithBLOBs;
import com.sliansoft.wechat.appcenter.service.IAppService;
import com.sliansoft.wechat.appcenter.service.IMenuOneService;
import com.sliansoft.wechat.appcenter.service.IMenuTwoService;
import com.sliansoft.wechat.appcenter.service.ISuiteService;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/manager")
public class ManagerController {

	@Inject
	private ISuiteService suiteService;

	@Inject
	private IAppService appService;

	@Inject
	private IMenuOneService menuoneService;

	@Inject
	private IMenuTwoService menutwoService;

	@RequestMapping("/list")
	public String list(Model model) {
		// 取出所有的suite
		List<SuiteWithBLOBs> suiteList = suiteService.seletAll();
		Map<SuiteWithBLOBs, List<AppWithBLOBs>> map = new HashMap<SuiteWithBLOBs, List<AppWithBLOBs>>();
		for (int i = 0; i < suiteList.size(); i++) {
			// 取出每个套件中的应用list
			model.addAttribute("appList" + suiteList.get(i).getId(),
					appService.selectBySuiteId(suiteList.get(i).getSuiteId()));
			map.put(suiteList.get(i), appService.selectBySuiteId(suiteList.get(i).getSuiteId()));
		}
		model.addAttribute("appList", map);
		return "manager/managerListSuite";
	}

	@RequestMapping(value = "/addSuite", method = RequestMethod.GET)
	public String addSuite() {
		return "manager/suiteAdd";
	}

	@RequestMapping(value = "/addSuite", method = RequestMethod.POST)
	public String addSuite(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html; charset=UTF-8");
		try {
			InputStream in = req.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
			String suitestr = "";
			String len = "";
			while ((len = br.readLine()) != null) {
				suitestr += len;
			}
			JSONObject jsonObject1 = JSONObject.fromObject(suitestr);
			@SuppressWarnings("unchecked")
			Map<String, String> map_result = JSONObject.fromObject(jsonObject1);

			System.out.println(map_result);

			SuiteWithBLOBs suite = new SuiteWithBLOBs();
			suite.setSuiteId(map_result.get("suiteid"));
			suite.setSuiteName(map_result.get("suitename"));
			suite.setSuiteSecret(map_result.get("suitesecret"));
			suite.setToken(map_result.get("suitetoken"));
			suite.setEncodingaeskey(map_result.get("suiteencodingaeskey"));
			suite.setSuiteIntroduction(map_result.get("suitedescription"));
			suite.setSuiteScene(map_result.get("suitescene"));
			suite.setSuiteLogoname(map_result.get("suitelogoname"));
			suiteService.add(suite);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "redirect:/manager/list";
	}

	@RequestMapping(value = "/deleteSuite/{id}", method = RequestMethod.GET)
	public String deleteSuiteGet(@PathVariable int id) {
		SuiteWithBLOBs suiteb = suiteService.selectById(id);
		List<AppWithBLOBs> list = appService.selectBySuiteId(suiteb.getSuiteId());
		if (list.size() != 0) {
			throw new SuiteException("套件中还存在应用，不能删除！");
		}
		suiteService.delete(id);
		return "redirect:/manager/list";
	}

	@RequestMapping(value = "/addApp/{id}", method = RequestMethod.GET)
	public String addApp(@PathVariable int id, Model model) {
		SuiteWithBLOBs suite = suiteService.selectById(id);
		model.addAttribute("suiteId", suite.getId());
		return "manager/appAdd";
	}

	@RequestMapping(value = "/addApp", method = RequestMethod.POST)
	public void addApp(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html; charset=UTF-8");
		PrintWriter out = resp.getWriter();
		AppWithBLOBs app = new AppWithBLOBs();
		try {
			InputStream in = req.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
			String appstr = "";
			String len = "";
			while ((len = br.readLine()) != null) {
				appstr += len;
			}
			JSONObject jsonObject1 = JSONObject.fromObject(appstr);
			@SuppressWarnings("unchecked")
			Map<String, String> map = JSONObject.fromObject(jsonObject1);
			System.out.println(map);

			app.setAppName(map.get("appname"));
			app.setCallbackurl(map.get("callbackurl"));
			app.setAppIntroduction(map.get("appdescription"));
			app.setAppScene(map.get("appscene"));
			app.setAppLogoname(map.get("applogoname"));
			app.setAppId(Integer.parseInt(map.get("appid")));
			app.setAppSuiteId(suiteService.selectById(Integer.parseInt(map.get("suiteId"))).getSuiteId());
			appService.add(app);

		} catch (Exception e) {
			e.printStackTrace();
		}
		out.print(app.getId());
		out.flush();
		out.close();
	}

	@RequestMapping(value = "/addMenuone")
	public void addMenuone(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html; charset=UTF-8");
		PrintWriter out = resp.getWriter();
		Menuone menuone = new Menuone();
		try {
			InputStream in = req.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
			String appstr = "";
			String len = "";
			while ((len = br.readLine()) != null) {
				appstr += len;
			}
			JSONObject jsonObject1 = JSONObject.fromObject(appstr);
			@SuppressWarnings("unchecked")
			Map<String, String> map = JSONObject.fromObject(jsonObject1);
			System.out.println(map);

			menuone.setMenuoneName(map.get("menuonename"));
			menuone.setMenuoneType(map.get("menuonetype"));
			menuone.setMenuoneKey(map.get("menuonekey"));
			menuone.setMenuoneUrl(map.get("menuoneurl"));
			menuone.setMenuoneAppId(Integer.valueOf(map.get("pre_app_id")));
			menuoneService.addMenuOne(menuone);
		} catch (Exception e) {
			e.printStackTrace();
		}
		out.print(menuone.getId());
		out.flush();
		out.close();
	}

	@RequestMapping(value = "/addMenutwo")
	public void addMenutwo(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html; charset=UTF-8");
		// PrintWriter out = resp.getWriter();
		Menutwo menutwo = new Menutwo();
		try {
			InputStream in = req.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
			String appstr = "";
			String len = "";
			while ((len = br.readLine()) != null) {
				appstr += len;
			}
			JSONObject jsonObject1 = JSONObject.fromObject(appstr);
			@SuppressWarnings("unchecked")
			Map<String, String> map = JSONObject.fromObject(jsonObject1);

			menutwo.setMenutwoName(map.get("menutwoname"));
			menutwo.setMenutwoType(map.get("menutwotype"));
			menutwo.setMenutwoUrl(map.get("menutwourl"));
			menutwo.setMenutwoKey(map.get("menutwokey"));
			menutwo.setMenutwoMenuoneId(Integer.parseInt(map.get("menuoneid")));
			menutwoService.addMenutwo(menutwo);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// out.print(menuone.getId());
		// out.flush();
		// out.close();
	}

	@RequestMapping(value = "deleteApp/{appId}", method = RequestMethod.GET)
	public String deleteApp(@PathVariable("appId") int appId) {
		List<Menuone> list = menuoneService.selectByAppId(appId);
		// 删除所有的二级菜单
		for (Menuone menuone : list) {
			menutwoService.deleteMenutwosByMenuone(menuone.getId());
		}
		// 删除所有的一级菜单
		menuoneService.deleteMenuonesByAppId(appId);

		// 删除该应用
		appService.delete(appId);
		return "redirect:/manager/list";
	}

	@RequestMapping("/uploadify")
	public void uploadFile(HttpServletRequest request, HttpServletResponse response, HttpSession session)
			throws Exception {

		String type = request.getParameter("type");
		String ret_fileName = null;// 返回给前端已修改的图片名称

		// 临时文件路径
		String dirTemp = "/static/upload/temp";

		String suitelogo = "";
		if ("app".equals(type)) {
			suitelogo = "/static/upload/applogo";
		} else if ("suite".equals(type)) {
			suitelogo = "/static/upload/suitelogo";
		} else {
			suitelogo = dirTemp;
		}

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = response.getWriter();

		// 获取当前应用的根目录
		String realPath = session.getServletContext().getRealPath("");
		// String tempPath = session.getServletContext().getRealPath("/") +
		// dirTemp;

		File realFile = new File(realPath);

		// 获取tomcat下的ROOT目录
		String rootPath = realFile.getParent() + "/ROOT";
		String normPath = rootPath + suitelogo;
		String tempPath = rootPath + dirTemp;

		File f = new File(normPath);
		File f1 = new File(tempPath);
		System.out.println(normPath);
		if (!f.exists()) {
			f.mkdirs();
		}

		if (!f1.exists()) {
			f1.mkdirs();
		}

		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(20 * 1024 * 1024); // 设定使用内存超过5M时，将产生临时文件并存储于临时目录中。
		factory.setRepository(new File(tempPath)); // 设定存储临时文件的目录。

		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("UTF-8");

		try {
			List<?> items = upload.parseRequest(request);
			Iterator<?> itr = items.iterator();

			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				String fileName = item.getName();
				if (fileName != null) {
					fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
					fileName = getUUID() + fileName;
					ret_fileName = fileName;
				}
				if (!item.isFormField()) {

					try {
						File uploadedFile = new File(normPath + "/" + fileName);
						OutputStream os = new FileOutputStream(uploadedFile);
						InputStream is = item.getInputStream();
						byte buf[] = new byte[1024];// 可以修改 1024 以提高读取速度
						int length = 0;
						while ((length = is.read(buf)) > 0) {
							os.write(buf, 0, length);
						}
						// 关闭流
						os.flush();
						os.close();
						is.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}

		} catch (FileUploadException e) {
			e.printStackTrace();
		}
		// 将已修改的图片名称返回前端
		out.print(ret_fileName);
		out.flush();
		out.close();
	}

	@RequestMapping("/getimage")
	public void getImage(HttpServletRequest req, HttpServletResponse resp, HttpSession session) throws Exception {
		String file = req.getParameter("file");
		String type = req.getParameter("type");
		String suitelogo = "";
		if ("app".equals(type)) {
			suitelogo = "/static/upload/applogo";
		} else if ("suite".equals(type)) {
			suitelogo = "/static/upload/suitelogo";
		}
		// 获取当前应用的根目录
		String realPath = session.getServletContext().getRealPath("");

		File realFile = new File(realPath);

		// 获取tomcat下的ROOT目录
		String rootPath = realFile.getParent() + "/ROOT";
		File pic = new File(rootPath + suitelogo + "/" + file);

		FileInputStream fis = new FileInputStream(pic);
		OutputStream os = resp.getOutputStream();
		try {
			int count = 0;
			byte[] buffer = new byte[1024 * 1024];
			while ((count = fis.read(buffer)) != -1)
				os.write(buffer, 0, count);
			os.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (os != null)
				os.close();
			if (fis != null)
				fis.close();
		}
	}

	private String getUUID() {
		return UUID.randomUUID().toString();
	}
}
